﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace PWEditor
{
    class XMLInterpreter
    {

        public static Map LoadMap(string path)
        {
            XDocument xDoc = XDocument.Load(path);
            
            //Define map size
            int rows = int.Parse(xDoc.Element("map").Attribute("rows").Value);
            int cols = int.Parse(xDoc.Element("map").Attribute("cols").Value);
            Map map = new Map(rows, cols);

            //If a tile is occupied (ie. defined in the map file) add it to the map
            foreach(XElement element in xDoc.Descendants("tile")){
                Tile tile = new Tile();
                int row = int.Parse(element.Attribute("row").Value);
                int col = int.Parse(element.Attribute("col").Value);
                map.SetTile(tile, row, col);   
            }

            return map;
        }

        public static void SaveMap(Map map, String path)
        {
            XElement tileElements = new XElement("tiles");
            foreach (Tile tile in map.Tiles)
            {
                if (tile != null)
                {
                    XElement tileElement = new XElement("tile", new XAttribute("row", tile.Row), new XAttribute("col", tile.Col));
                    tileElements.Add(tileElement);
                }
            }
            

            XDocument xDoc =    new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                                    new XElement("map", 
                                        new XAttribute("rows",map.Rows), 
                                        new XAttribute("cols", map.Cols), 
                                        tileElements)
                                        );
            xDoc.Save(path);
        }

    }
}
